package model

import (
	"fmt"
	"github.com/go-redis/redis"
	. "leaf/cache"
	"leaf/core/tool"
	"leaf/pb"
)

type StatusModel struct {
	UserId uint64
	Status *pb.GamerStatus
}

func NewStatusModel(userId uint64) *StatusModel {
	var cache = GetCache()
	if cache == nil {
		return nil
	}

	s := &StatusModel{
		UserId: userId,
		Status: new(pb.GamerStatus),
	}

	var key = fmt.Sprintf(GAMER_STATUS, GetKeyPrefix(), s.UserId)
	var data, err = cache.Get(key).Result()
	if err == redis.Nil {
		return s
	}

	if err != nil {
		return nil
	}

	if !tool.ParseDBStr(data, s.Status) {
		return nil
	}
	return s
}

func (s StatusModel) Save() bool {
	var cache = GetCache()
	if cache == nil {
		return false
	}

	var key = fmt.Sprintf(GAMER_STATUS, GetKeyPrefix(), s.UserId)
	var err = cache.Set(key, tool.DBStr(s.Status), 0).Err()
	if err != nil {
		return false
	}

	return true
}
